import 'dart:io';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:webview_flutter/webview_flutter.dart';

const String baseUrl = String.fromEnvironment('BASE_URL');
class DyCookieManager extends Interceptor {
  static DyCookieManager? _instance;

  static WebViewCookie? webViewCookie;

  DyCookieManager._();

  factory DyCookieManager() {
    return _instance ??= DyCookieManager._();
  }

  @override
  void onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    var cookie = await getCookies();
    if (cookie.isNotEmpty) {
      options.headers[HttpHeaders.cookieHeader] = cookie;
    }
    handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    _saveCookies(response)
        .then((_) => handler.next(response))
        .catchError((e, stackTrace) {
      var err = DioException(requestOptions: response.requestOptions, error: e, stackTrace: stackTrace);
      handler.reject(err, true);
    });
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    if (err.response != null) {
      _saveCookies(err.response!)
          .then((_) => handler.next(err))
          .catchError((e, stackTrace) {
        var err0 = DioException(
          requestOptions: err.response!.requestOptions,
          error: e,
          stackTrace: stackTrace,
        );
        handler.next(err0);
      });
    } else {
      handler.next(err);
    }
  }

  Future<void> _saveCookies(Response response) async {
    var prefs = await SharedPreferences.getInstance();
    var cookies = response.headers[HttpHeaders.setCookieHeader];

    if (cookies != null) {
      prefs.setString('dy_cookie', cookies[0]);
    }
  }

  /// 获取cookie字符串
  static Future<String> getCookies() async {
    var prefs = await SharedPreferences.getInstance();
    final dyCookie = prefs.getString('dy_cookie') ?? '';
    webViewCookie = dyCookie.isNotEmpty ? _getWebViewCookie(dyCookie) : null;
    return dyCookie;
  }

  /// 删除cookie
  static deleteCookies() async {
    var prefs = await SharedPreferences.getInstance();
    prefs.remove('dy_cookie');
  }

  /// WebViewCookie
  static WebViewCookie _getWebViewCookie(cookie) {
    int len = cookie.indexOf('=');
    String name = cookie.substring(0, len);
    cookie = cookie.substring(len);
    len = cookie.indexOf(';');
    String value = cookie.substring(1, len);
    cookie = cookie.substring(len + 1);
    return WebViewCookie(
      name: name,
      value: value,
      domain: Uri.parse(baseUrl).host,
    );
  }
}
